package com.loong.web.suppert.auth;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.loong.tool.secret.security.digest.Digest;

/**
 * 用户Cookie工具类
 *
 * @author 张成轩
 */
public class UserCookies {

	/** 用户id参数名 */
	private static final String ATTR_UID = "_uid";

	/** 校验签名参数名 */
	private static final String ATTR_UV = "_uv";

	/**
	 * 添加用户Cookie
	 * 
	 * @param request 请求
	 * @param response 响应
	 * @param uid 用户标志
	 */
	public static void setUser(HttpServletRequest request, HttpServletResponse response, String uid) {

		String agent = request.getHeader("User-Agent");
		String v = Digest.digest(agent + uid);
		// 添加Cookie
		addCookie(request, response, ATTR_UID, uid);
		addCookie(request, response, ATTR_UV, v);
	}

	/**
	 * 获取用户
	 * 
	 * @param request 请求
	 * @param response 相应
	 * @return 用户id
	 */
	public static String getUser(HttpServletRequest request, HttpServletResponse response) {

		String uid = null;
		String uv = null;
		Cookie[] cookies = request.getCookies();
		if (cookies == null)
			return null;
		for (Cookie cookie : cookies) {
			if (uid != null && uv != null)
				break;
			if (ATTR_UID.equals(cookie.getName())) {
				uid = cookie.getValue();
				continue;
			}
			if (ATTR_UV.equals(cookie.getName()))
				uv = cookie.getValue();
		}
		if (uid == null || uv == null)
			return null;

		// 校验验证符
		String agent = request.getHeader("User-Agent");
		String v = Digest.digest(agent + uid);
		if (!v.equals(uv)) {
			removeUser(request, response);
			return null;
		}
		return uid;
	}

	/**
	 * 移除用户Cookie
	 * 
	 * @param request 请求
	 * @param response 响应
	 */
	public static void removeUser(HttpServletRequest request, HttpServletResponse response) {

		removeCookie(request, response, ATTR_UID);
		removeCookie(request, response, ATTR_UV);
	}

	/**
	 * 添加Cookie
	 * 
	 * @param request 请求
	 * @param response 响应
	 * @param name 名称
	 * @param value 值
	 */
	private static void addCookie(HttpServletRequest request, HttpServletResponse response, String name, String value) {

		Cookie cookie = new Cookie(name, value);
		cookie.setPath(request.getContextPath() + "/");
		cookie.setMaxAge(2592000);
		response.addCookie(cookie);
	}

	/**
	 * 移除Cookie
	 * 
	 * @param request 请求
	 * @param response 响应
	 * @param name 名称
	 */
	private static void removeCookie(HttpServletRequest request, HttpServletResponse response, String name) {

		Cookie cookie = new Cookie(name, null);
		cookie.setMaxAge(0);
		cookie.setPath(request.getContextPath() + "/");
		response.addCookie(cookie);
	}
}
